package com.stars.easyms.logging.ansi;

import com.stars.easyms.base.util.PatternUtil;
import org.apache.commons.lang3.StringUtils;

import static com.stars.easyms.logging.constant.EasyMsLoggingConstants.*;

/**
 * <p>className: EasyMsAnsiGenerator</p>
 * <p>description: ansi生成者</p>
 *
 * @author guoguifang
 * @version 1.7.2
 * @date 2021/1/28 12:02 上午
 */
public final class EasyMsAnsiGenerator {

    public static String getAnsiStr(String colorStr) {
        if (StringUtils.isNotBlank(colorStr)) {
            colorStr = colorStr.trim().toUpperCase();
            String[] splitColorStrArray = PatternUtil.splitWithCommaOrWhitespace(colorStr);
            if (splitColorStrArray.length > 0) {
                StringBuilder sb = new StringBuilder();
                boolean writingAnsi = false;
                for (String s : splitColorStrArray) {
                    String code;
                    EasyMsAnsiEnum easyMsAnsiEnum = EasyMsAnsiEnum.of(s);
                    if (easyMsAnsiEnum != null) {
                        code = easyMsAnsiEnum.getCode();
                    } else {
                        code = EasyMsAnsi8BitColor.getCode(s);
                    }
                    if (code != null) {
                        if (writingAnsi) {
                            sb.append(ENCODE_JOIN);
                        } else {
                            sb.append(ENCODE_START);
                            writingAnsi = true;
                        }
                        sb.append(code);
                    }
                }
                if (writingAnsi) {
                    sb.append(ENCODE_END);
                }
                return sb.toString();
            }
        }
        return "";
    }

    private EasyMsAnsiGenerator() {
    }
}
